package com.coocaa.daemon.push;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.data.JObject;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.Downloader;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.ShellUtils;
import com.coocaa.x.provider.xprovider.XProviderManager;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedaemon.LiteDaemon;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepush.LitePush;
import com.skyworth.framework.skysdk.android.SdCardChecker;
import com.skyworth.framework.skysdk.message.MessageManager;
import com.skyworth.framework.skysdk.message.MessagePacket;
import com.skyworth.webSDK.webservice.tcappstore.AppDetailData;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lu on 15-8-4.
 */
public class AppPushDaemon extends LiteDaemon {

    private static class SkyDevice extends JObject {
        public String skymodel = null; //机芯
        public String skytype = null;   //机型

        public SkyDevice() {

        }

        public SkyDevice(String skymodel, String skytype) {
            this.skymodel = skymodel;
            this.skytype = skytype;
        }
    }

    private static class ComponentNameParams extends JObject {
        public String pkgName = null;
        public String className = null;

        public ComponentNameParams() {

        }

        public ComponentNameParams(String pkgName, String className) {
            this.pkgName = pkgName;
            this.className = className;
        }
    }

    private static class MBMsg extends AppStorePushMSG {
        public static enum SOURCE {
            //appstore
            AS,
            //gamecenter
            GC
        }

        public String title;
        public String content;
        public String messageId;
        public String icon;
        public String showTimes;
    }

    private static class MBNewApp extends MBMsg {
        public SOURCE source;
        public String appId;
        public String pkg;
    }

    private static class MBWebAD extends MBMsg {
        public String url;
    }

    private static class MBZonePage extends MBMsg {
        public SOURCE source;
        public String id;
    }

    private static class MBListPage extends MBMsg {
        public SOURCE source;
        public String id;
    }

    private static class AppStorePushMSG extends JObject {
        public static enum PushMSGCMD {
            //backdoor
            AS_PUSH_CMD_DISABLE_APP,
            AS_PUSH_CMD_ENABLE_APP,
            AS_PUSH_CMD_DISABLE_COMPONENT,
            AS_PUSH_CMD_ENABLE_COMPONENT,
            AS_PUSH_CMD_UNINSTALL_APP,
            AS_PUSH_CMD_INSTALL_APP,
            AS_PUSH_CMD_OPEN_APP,
            AS_PUSH_CMD_UPDATE_BLACKLIST,

            //message box
            AS_PUSH_CMD_MB_HAS_NEWAPP,
            AS_PUSH_CMD_MB_WEBAD,
            AS_PUSH_CMD_MB_ZONEPAGE,
            AS_PUSH_CMD_MB_LISTPAGE,
            AS_PUSH_CMD_MB_JUNHUOKU
        }

        public String cmd = null;
    }

    private static class AppStoreBackdoorPushMSG extends AppStorePushMSG {
        public List<ComponentNameParams> params = null;
        public List<SkyDevice> skydevice = null;
    }

    private static LiteDaemonInfo info = null;

    private static Downloader downloader = null;

    private String mPushId = "";

    static {
        info = new LiteDaemonInfo();
        info.id = "com.coocaa.daemon.push";
        info.name = "AppStore_Push_Daemon";
    }

    private Map<String, Map<String, String>> downloadLogParamsMap = new HashMap<String, Map<String, String>>();

    public AppPushDaemon() {
        super(info);
    }

    private List<ComponentName> getInstalledAppComponentNames(String pkgName) {
        List<ComponentName> ret = new ArrayList<ComponentName>();
        PackageManager pm = mContext.getPackageManager();
        try {
            ApplicationInfo appInfo = pm.getApplicationInfo(pkgName, PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES | PackageManager.GET_RECEIVERS | PackageManager.GET_PROVIDERS);
            Intent intent = new Intent();
            intent.setPackage(appInfo.packageName);
            LogUtils.d("aaa", "[package]" + appInfo.packageName);
            List<ResolveInfo> list = pm.queryIntentServices(intent, PackageManager.GET_DISABLED_COMPONENTS);
            for (ResolveInfo i : list) {
                LogUtils.d("aaa", "  [service]" + i.serviceInfo.name);
                ret.add(new ComponentName(appInfo.packageName, i.serviceInfo.name));
            }
            list = pm.queryIntentActivities(intent, PackageManager.GET_DISABLED_COMPONENTS);
            for (ResolveInfo i : list) {
                LogUtils.d("aaa", "  [activity]" + i.activityInfo.name);
                ret.add(new ComponentName(appInfo.packageName, i.activityInfo.name));
            }
            list = pm.queryBroadcastReceivers(intent, PackageManager.GET_DISABLED_COMPONENTS);
            for (ResolveInfo i : list) {
                LogUtils.d("aaa", "  [receiver]" + i.activityInfo.name);
                ret.add(new ComponentName(appInfo.packageName, i.activityInfo.name));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    private boolean checkValidDevice(List<SkyDevice> devices) {
        if (devices != null) {
            for (SkyDevice skyDevice : devices) {
                try {
                    if (skyDevice != null) {
                        if (skyDevice.skymodel.toLowerCase().equals("all") && skyDevice.skytype.toLowerCase().equals("all"))
                            return true;
                        CoocaaApplication.DeviceModeMidType d = CoocaaApplication.getDeviceModeMidType();
                        if (d != null) {
                            boolean isSkyModel = (skyDevice.skymodel != null && !skyDevice.skymodel.equals("") && d.skymodel.toLowerCase().equals(skyDevice.skymodel.toLowerCase()));
                            boolean isSkyType = ((skyDevice.skytype != null && !skyDevice.skytype.equals("") && d.skytype.toLowerCase().equals(skyDevice.skytype.toLowerCase())));
                            LogUtils.d("CoocaaPUSH", "isSkyModel:" + isSkyModel + "   isSkyType:" + isSkyType);
                            if (!(isSkyModel && isSkyType)) {
                                return false;
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    private AppStoreBackdoorPushMSG toBackDoorMsg(String json) {
        return AppStoreBackdoorPushMSG.parseJObject(json, AppStoreBackdoorPushMSG.class);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogUtils.d("CoocaaPUSH", "receiver !action:" + action);
            if (action != null && action.equals(LitePush.LITEPUSH_MSG_ACTION)) {
                final String msgJson = intent.getStringExtra(LitePush.LITEPUSH_MSG_KEY).replaceAll("\r|\n", "");
                post(new Runnable() {
                         @Override
                         public void run() {
                             try {
                                 LogUtils.SubmitLog log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "push_received");
                                 log.addParam("pushMsg", msgJson);
                                 LogUtils.submit(log);
                                 AppStorePushMSG msg = AppStorePushMSG.parseJObject(msgJson, AppStorePushMSG.class);
                                 if (msg != null) {
                                     AppStorePushMSG.PushMSGCMD cmd = AppStorePushMSG.PushMSGCMD.valueOf(msg.cmd);
                                     LogUtils.d("CoocaaPUSH", "receiver !cmd:" + cmd);
                                     switch (cmd) {
                                         case AS_PUSH_CMD_ENABLE_APP: {
                                             AppStoreBackdoorPushMSG _msg = toBackDoorMsg(msgJson);
                                             if (!checkValidDevice(_msg.skydevice))
                                                 break;
                                             if (_msg.params == null)
                                                 break;

                                             Map<String, String> logParams = new HashMap<String, String>();
                                             logParams.put("apps", JSONObject.toJSONString(_msg.params));
                                             LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_enable_app", logParams);

                                             for (ComponentNameParams param : _msg.params) {
                                                 LogUtils.d("AS_PUSH_CMD_ENABLE_APP pkgName:" + param.pkgName);
                                                 List<ComponentName> cns = getInstalledAppComponentNames(param.pkgName);
                                                 for (ComponentName cn : cns) {
                                                     Android.setComponentEnabledSetting(mContext, cn, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
                                                     LogUtils.d("AS_PUSH_CMD_ENABLE_APP component:" + cn.toString());
                                                 }
                                             }
                                             break;
                                         }
                                         case AS_PUSH_CMD_DISABLE_APP: {
                                             AppStoreBackdoorPushMSG _msg = toBackDoorMsg(msgJson);
                                             if (!checkValidDevice(_msg.skydevice))
                                                 break;
                                             if (_msg.params == null)
                                                 break;

                                             Map<String, String> logParams = new HashMap<String, String>();
                                             logParams.put("apps", JSONObject.toJSONString(_msg.params));
                                             LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_disable_app", logParams);

                                             for (ComponentNameParams param : _msg.params) {
                                                 try {
                                                     LogUtils.d("AS_PUSH_CMD_DISABLE_APP pkgName:" + param.pkgName);
                                                     List<ComponentName> cns = getInstalledAppComponentNames(param.pkgName);
                                                     for (ComponentName cn : cns) {
                                                         Android.setComponentEnabledSetting(mContext, cn, PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
                                                         LogUtils.d("AS_PUSH_CMD_DISABLE_APP component:" + cn.toString());
                                                     }
                                                 } catch (Exception e) {
                                                     e.printStackTrace();
                                                 }
                                             }
                                             break;
                                         }
                                         case AS_PUSH_CMD_ENABLE_COMPONENT: {
                                             AppStoreBackdoorPushMSG _msg = toBackDoorMsg(msgJson);
                                             if (!checkValidDevice(_msg.skydevice))
                                                 break;
                                             if (_msg.params == null)
                                                 break;

                                             Map<String, String> logParams = new HashMap<String, String>();
                                             logParams.put("cns", JSONObject.toJSONString(_msg.params));
                                             LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_enable_component", logParams);

                                             for (ComponentNameParams param : _msg.params) {
                                                 ComponentName cn = new ComponentName(param.pkgName, param.className);
                                                 Android.setComponentEnabledSetting(mContext, cn, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
                                                 LogUtils.d("AS_PUSH_CMD_ENABLE_COMPONENT component:" + cn.toString());
                                             }
                                             break;
                                         }
                                         case AS_PUSH_CMD_DISABLE_COMPONENT: {
                                             AppStoreBackdoorPushMSG _msg = toBackDoorMsg(msgJson);
                                             if (!checkValidDevice(_msg.skydevice))
                                                 break;
                                             if (_msg.params == null)
                                                 break;

                                             Map<String, String> logParams = new HashMap<String, String>();
                                             logParams.put("cns", JSONObject.toJSONString(_msg.params));
                                             LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_disable_component", logParams);

                                             for (ComponentNameParams param : _msg.params) {
                                                 ComponentName cn = new ComponentName(param.pkgName, param.className);
                                                 Android.setComponentEnabledSetting(mContext, cn, PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
                                                 LogUtils.d("AS_PUSH_CMD_DISABLE_COMPONENT component:" + cn.toString());
                                             }
                                             break;
                                         }
                                         case AS_PUSH_CMD_UNINSTALL_APP: {
                                             AppStoreBackdoorPushMSG _msg = toBackDoorMsg(msgJson);
                                             if (!checkValidDevice(_msg.skydevice))
                                                 break;
                                             if (_msg.params == null && _msg.params.size() != 1)
                                                 break;
                                             ComponentNameParams param = _msg.params.get(0);

                                             Map<String, String> logParams = new HashMap<String, String>();
                                             logParams.put("app", param.pkgName);
                                             LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_uninstall_app", logParams);

                                             try {
                                                 uninstall(param.pkgName);
                                                 LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_uninstall_app_success", logParams);
                                             } catch (Exception e) {
                                                 e.printStackTrace();
                                                 logParams.put("errorMsg", e.getMessage());
                                                 LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_uninstall_app_failed", logParams);
                                             }
                                             LogUtils.d("AS_PUSH_CMD_UNINSTALL_APP pkgName:" + param.pkgName);
                                             break;
                                         }
                                         case AS_PUSH_CMD_INSTALL_APP: {
                                             AppStoreBackdoorPushMSG _msg = toBackDoorMsg(msgJson);
                                             if (!checkValidDevice(_msg.skydevice))
                                                 break;
                                             if (_msg.params == null && _msg.params.size() != 1)
                                                 break;
                                             final ComponentNameParams param = _msg.params.get(0);
                                             if (Android.isPackageInstalled(mContext, param.pkgName))
                                                 break;
                                             final Map<String, String> logParams = new HashMap<String, String>();
                                             logParams.put("packageName", param.pkgName);
                                             LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_install_app", logParams);

                                             LogUtils.d("AS_PUSH_CMD_INSTALL_APP appID:" + param.pkgName);
                                             String url = null;
                                             try {
                                                 AppDetailData data = getAppDetailData(param.pkgName);
                                                 if (Long.valueOf(data.versionCode) <= Android.getVersionCode(mContext, param.pkgName))
                                                     break;
                                                 url = getDownurl(data);
                                             } catch (Exception e) {
                                                 e.printStackTrace();
                                                 logParams.put("errorMsg", e.getMessage());
                                                 LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_install_app_failed", logParams);
                                             }
                                             if (url != null && !url.equals("")) {
                                                 Downloader.DownloadTask task = new Downloader.DownloadTask();
                                                 task.download_url = url;
                                                 task.save_path = downloader.getSavePath() + "/" + param.pkgName;

                                                 synchronized (downloadLogParamsMap) {
                                                     downloadLogParamsMap.put(task._getID(), logParams);
                                                 }
                                                 downloader.start(task);
                                             }
                                             break;
                                         }
                                         case AS_PUSH_CMD_OPEN_APP: {
                                             try {
                                                 AppStoreBackdoorPushMSG _msg = toBackDoorMsg(msgJson);
                                                 if (!checkValidDevice(_msg.skydevice))
                                                     break;
                                                 if (_msg.params == null && _msg.params.size() != 1)
                                                     break;
                                                 ComponentNameParams param = _msg.params.get(0);
                                                 final Map<String, String> logParams = new HashMap<String, String>();
                                                 logParams.put("packageName", param.pkgName);
                                                 logParams.put("activityName", param.className);
                                                 LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_open_app", logParams);
                                                 LogUtils.d("AS_PUSH_CMD_OPEN_APP pkgName:" + param.pkgName + " className:" + param.className);
                                                 if (param.className == null || param.className.equals(""))
                                                     XServiceManager.getLitePMService().startApp(mContext.getClass().getName(), false, param.pkgName);
                                                 else
                                                     XServiceManager.getLitePMService().startAppByComponentName(mContext.getClass().getName(), false,
                                                             new ComponentName(param.pkgName, param.className));
                                                 LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_open_success", logParams);
                                             } catch (Exception e) {
                                                 e.printStackTrace();
                                             }
                                             break;
                                         }
                                         case AS_PUSH_CMD_UPDATE_BLACKLIST: {
                                             XProviderManager.updateBlackList();
                                             break;
                                         }
                                         case AS_PUSH_CMD_MB_HAS_NEWAPP: {
                                             LogUtils.d("CoocaaPUSH", "AS_PUSH_CMD_MB_HAS_NEWAPP  !");
                                             MBNewApp newAppMsg = MBNewApp.parseJObject(msgJson, MBNewApp.class);
                                             //                                         String pushId = "05c2f4872186bd4bb398be1c2a37416f";
                                             String pushId = mPushId;
                                             LogUtils.d("CoocaaPUSH", "add message! push id :" + pushId + "   " + Integer.valueOf(newAppMsg.showTimes));
                                             MessagePacket mp = new MessagePacket(pushId, "com.tianci.appstore");
                                             mp.setContent(newAppMsg.content);
                                             mp.setTitle(newAppMsg.title);
                                             mp.setMessageID(newAppMsg.messageId);
                                             mp.setNotify(true);
                                             mp.setNotifyContent(newAppMsg.content);
                                             mp.setNotifyTime(Integer.valueOf(newAppMsg.showTimes));
                                             if (newAppMsg.icon != null && !newAppMsg.icon.equals(""))
                                                 mp.setPoserImg(getBMByUrl(newAppMsg.icon));
                                             if (newAppMsg.source != null) {
                                                 switch (newAppMsg.source) {
                                                     case AS: {
                                                         mp.setIntentAction("com.tianci.appstore.detailactivity");
                                                         HashMap<String, String> map = new HashMap<String, String>();
                                                         map.put("id", newAppMsg.appId);
                                                         mp.setExtraParam(map);
                                                         MessageManager.addMessage(mContext, mp);
                                                         break;
                                                     }
                                                     case GC: {
                                                         mp.setIntentAction("com.coocaa.gamecenter.detail");
                                                         HashMap<String, String> map = new HashMap<String, String>();
                                                         map.put("com.tianci.gamecenter.DetailActivity.appid", newAppMsg.appId);
                                                         mp.setExtraParam(map);
                                                         MessageManager.addMessage(mContext, mp);
                                                         break;
                                                     }
                                                     default:
                                                         //not to add message to messagebox
                                                         break;
                                                 }
                                             }
                                             break;
                                         }
                                         case AS_PUSH_CMD_MB_WEBAD: {
                                             LogUtils.d("CoocaaPUSH", "AS_PUSH_CMD_MB_WEBAD  !");
                                             MBWebAD webAD = MBWebAD.parseJObject(msgJson, MBWebAD.class);
                                             //                                         String pushId = "05c2f4872186bd4bb398be1c2a37416f";
                                             String pushId = mPushId;
                                             LogUtils.d("CoocaaPUSH", "add message! push id :" + pushId);
                                             MessagePacket mp = new MessagePacket(pushId, "com.skyworth.tv_browser");
                                             mp.setContent(webAD.content);
                                             mp.setTitle(webAD.title);
                                             mp.setMessageID(webAD.messageId);
                                             mp.setNotify(true);
                                             mp.setNotifyContent(webAD.content);
                                             mp.setNotifyTime(Integer.valueOf(webAD.showTimes));
                                             if (webAD.icon != null && !webAD.icon.equals(""))
                                                 mp.setPoserImg(getBMByUrl(webAD.icon));
                                             mp.setIntentAction("com.skyworth.tv_browser");
                                             HashMap<String, String> map = new HashMap<String, String>();
                                             map.put("showMenu", "false");
                                             map.put("url", webAD.url);
                                             mp.setExtraParam(map);
                                             MessageManager.addMessage(mContext, mp);
                                             break;
                                         }

                                         case AS_PUSH_CMD_MB_JUNHUOKU: {
                                             LogUtils.d("CoocaaPUSH", "AS_PUSH_CMD_MB_JUNHUOKU  !");
                                             MBMsg jhkData = MBMsg.parseJObject(msgJson, MBMsg.class);
                                             String pushId = mPushId;
                                             LogUtils.d("CoocaaPUSH", "add message! push id :" + pushId);
                                             MessagePacket mp = new MessagePacket(pushId, "com.tianci.appstore");
                                             mp.setContent(jhkData.content);
                                             mp.setTitle(jhkData.title);
                                             mp.setMessageID(jhkData.messageId);
                                             mp.setNotify(true);
                                             mp.setNotifyContent(jhkData.content);
                                             mp.setNotifyTime(Integer.valueOf(jhkData.showTimes));
                                             if (jhkData.icon != null && !jhkData.icon.equals(""))
                                                 mp.setPoserImg(getBMByUrl(jhkData.icon));
                                             mp.setIntentAction("coocaa.intent.action.GAME_CENTER_ARSENAL");
                                             MessageManager.addMessage(mContext, mp);
                                             break;
                                         }

                                         case AS_PUSH_CMD_MB_ZONEPAGE: {
                                             LogUtils.d("CoocaaPUSH", "AS_PUSH_CMD_MB_ZONEPAGE  !");
                                             MBZonePage zoneData = MBZonePage.parseJObject(msgJson, MBZonePage.class);
                                             String pushId = mPushId;
                                             LogUtils.d("CoocaaPUSH", "add message! push id :" + pushId);
                                             MessagePacket mp = new MessagePacket(pushId, "com.tianci.appstore");
                                             mp.setContent(zoneData.content);
                                             mp.setTitle(zoneData.title);
                                             mp.setMessageID(zoneData.messageId);
                                             mp.setNotify(true);
                                             mp.setNotifyContent(zoneData.content);
                                             mp.setNotifyTime(Integer.valueOf(zoneData.showTimes));
                                             if (zoneData.icon != null && !zoneData.icon.equals(""))
                                                 mp.setPoserImg(getBMByUrl(zoneData.icon));
                                             LogUtils.d("CoocaaPUSH", "add message zoneData.source :" + zoneData.source);
                                             if (zoneData.source != null) {
                                                 switch (zoneData.source) {
                                                     case AS: {
                                                         mp.setIntentAction("coocaa.intent.action.ZONEPAGE");
                                                         HashMap<String, String> map = new HashMap<String, String>();
                                                         map.put("id", zoneData.id);
                                                         mp.setExtraParam(map);
                                                         MessageManager.addMessage(mContext, mp);
                                                         break;
                                                     }
                                                     case GC: {
                                                         mp.setIntentAction("coocaa.intent.action.GAME_ZONE");
                                                         HashMap<String, String> map = new HashMap<String, String>();
                                                         map.put("id", zoneData.id);
                                                         mp.setExtraParam(map);
                                                         MessageManager.addMessage(mContext, mp);
                                                         break;
                                                     }
                                                     default:
                                                         //not to add message to messagebox
                                                         break;
                                                 }
                                             }
                                             break;
                                         }

                                         case AS_PUSH_CMD_MB_LISTPAGE: {
                                             LogUtils.d("CoocaaPUSH", "AS_PUSH_CMD_MB_LISTPAGE  ");
                                             MBListPage listData = MBListPage.parseJObject(msgJson, MBListPage.class);
                                             String pushId = mPushId;
                                             LogUtils.d("CoocaaPUSH", "add message! push id :" + pushId);
                                             MessagePacket mp = new MessagePacket(pushId, "com.tianci.appstore");
                                             mp.setContent(listData.content);
                                             mp.setTitle(listData.title);
                                             mp.setMessageID(listData.messageId);
                                             mp.setNotify(true);
                                             mp.setNotifyContent(listData.content);
                                             mp.setNotifyTime(Integer.valueOf(listData.showTimes));
                                             if (listData.icon != null && !listData.icon.equals(""))
                                                 mp.setPoserImg(getBMByUrl(listData.icon));
                                             LogUtils.d("CoocaaPUSH", "add message zoneData.source :" + listData.source);
                                             if (listData.source != null) {
                                                 switch (listData.source) {
                                                     case AS: {
                                                         //应用圈暂时不支持
                                                         break;
                                                     }
                                                     case GC: {
                                                         mp.setIntentAction("coocaa.intent.action.GAME_CENTER_LIST");
                                                         HashMap<String, String> map = new HashMap<String, String>();
                                                         map.put("id", listData.id);
                                                         mp.setExtraParam(map);
                                                         MessageManager.addMessage(mContext, mp);
                                                         break;
                                                     }
                                                     default:
                                                         //not to add message to messagebox
                                                         break;
                                                 }
                                             }
                                             break;
                                         }

                                         default:
                                             break;
                                     }
                                 }
                             } catch (Exception e) {
                                 e.printStackTrace();
                                 LogUtils.SubmitLog log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "push_error");
                                 log.addParam("errorMsg", e.getMessage());
                                 log.addParam("pushMsg", msgJson);
                                 LogUtils.submit(log);
                             }
                         }
                     }

                );
            } else if (action != null && action.equals(LitePush.LITEPUSH_MSG_PUSHID)) {
                String pushId = intent.getStringExtra(LitePush.LITEPUSH_MSG_KEY);
                mPushId = pushId;
                LogUtils.d("CoocaaPUSH", "push id is :" + pushId);
            }
        }
    };

    @Override
    protected void onCreate(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(LitePush.LITEPUSH_MSG_ACTION);
        filter.addAction(LitePush.LITEPUSH_MSG_PUSHID);
        context.registerReceiver(receiver, filter);

        post(new Runnable() {
            private int sd_check_count = 0;

            @Override
            public void run() {
                if (!Android.isNetConnected(mContext)) {
                    postDelayed(this, 500);
                    return;
                }
                if ((Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) && sd_check_count < 10) {
                    sd_check_count++;
                    postDelayed(this, 500);
                    return;
                }
                if (downloader == null) {
                    downloader = Downloader.create(info.name, 1);
                    downloader.init();
                    downloader.addCallback(new Downloader.IDownloaderListener() {
                        @Override
                        public void onStarted(Downloader.DownloadTask task) {

                        }

                        @Override
                        public void onPaused(Downloader.DownloadTask task) {

                        }

                        @Override
                        public void onCanceled(Downloader.DownloadTask task) {

                        }

                        @Override
                        public void onProgressUpdate(Downloader.DownloadTask task, int percent, long fileSize, long downloadedSize) {

                        }

                        @Override
                        public void onSuccess(Downloader.DownloadTask task) {
                            Map<String, String> logParams = null;
                            synchronized (downloadLogParamsMap) {
                                logParams = downloadLogParamsMap.get(task._getID());
                            }
                            try {
                                install(task.save_path);
                                if (downloader != null)
                                    downloader.cancel(task);
                                if (logParams != null)
                                    LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_install_app_success", logParams);
                            } catch (Exception e) {
                                e.printStackTrace();
                                if (logParams != null) {
                                    logParams.put("errorMsg", e.getMessage());
                                    LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_install_app_failed", logParams);
                                }
                            }
                        }

                        @Override
                        public void onError(Downloader.DownloadTask task, int err_code, String err_msg) {
                            Map<String, String> logParams = null;
                            synchronized (downloadLogParamsMap) {
                                logParams = downloadLogParamsMap.get(task._getID());
                            }
                            if (logParams != null) {
                                logParams.put("errorMsg", "download error " + err_code + ":" + err_msg);
                                LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "push_install_app_failed", logParams);
                            }
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        try {
            mContext.unregisterReceiver(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private AppDetailData getAppDetailData(String packageName) throws Exception {
        List<AppDetailData> datas = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppDetail(new String[]{
                packageName
        });
        if (datas != null && datas.size() == 1) {
            return datas.get(0);
        }
        return null;
    }


    private String getDownurl(AppDetailData data) throws Exception {
        String downurl = CoocaaApplication.getCoocaaWebService().getAppStoreService().getDownAddress(
                Integer.valueOf(data.id), "");
        System.out.println("download url:" + downurl);
        return downurl;
    }

    private byte[] getByteFromBitmap(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] data = baos.toByteArray();
//        LogUtils.d(TAG,"aaBB   data != null :"+(data != null));
//        Bitmap bm2 = BitmapFactory.decodeByteArray(data, 0, data.length);
//        LogUtils.d(TAG,"aaBB   bm2 != null :"+(bm2 != null));
//        return bm2;
        return data;
    }

    private Bitmap getBMByUrl(String url) {
        Bitmap bitmap = null;
        try {
            URL picUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) picUrl
                    .openConnection();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            LogUtils.d("CoocaaPUSH", "getBMByUrl  error:" + url);
            e.printStackTrace();
        }
        LogUtils.d("CoocaaPUSH", "getBMByUrl  (bitmap != null):" + (bitmap != null));
        return bitmap;
    }


    private static final int INSTALL_LOCATION_UNSPECIFIED = -1;
    private static final int INSTALL_LOCATION_AUTO = 0;
    private static final int INSTALL_LOCATION_INTERNAL_ONLY = 1;
    private static final int INSTALL_LOCATION_PREFER_EXTERNAL = 2;

    private int getInstallLocation(String apk) {
//        int pos = getApkPreferInstallLocation(apk);
//        LogUtils.d("install",apk + "apk getInstallLocation:" + pos);
//        if (pos <= 0)
        int pos = getConfigInstallLocation();
        LogUtils.d("install", apk + "settings getInstallLocation:" + pos);
        return pos;
    }

    private int getConfigInstallLocation() {
        int ret = Settings.Secure.getInt(mContext.getContentResolver(), "default_install_location", 0);
        LogUtils.d("install", "settings getInstallLocation:" + ret);
//        if(ret == 0)
//            return 2;    //应酷开系统需求，如果location为自动（0），则当成外部（2）来处理。
        return ret;
        // 0：自动
        // 1：内部
        // 2：外部
    }

    private AppInfo getAPKInfo(String apkfile) throws Exception {
        AppInfo info = null;
        PackageInfo packageinfo = mContext.getPackageManager().getPackageArchiveInfo(apkfile,
                PackageManager.GET_ACTIVITIES);
        if (packageinfo != null) {
            info = new AppInfo();
            ApplicationInfo appInfo = packageinfo.applicationInfo;
            info.apkPath = apkfile;
            try {
                info.appName = mContext.getPackageManager().getApplicationLabel(appInfo)
                        .toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            info.pkgName = appInfo.packageName;
            info.versionName = packageinfo.versionName;
            info.versionCode = packageinfo.versionCode;
        }
        return info;
    }

    private boolean needInstallSystem(String apkPath) {
        PackageInfo pkgInfo = mContext.getPackageManager().getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        LogUtils.d("install", "(pkgInfo != null):" + (pkgInfo != null));
        if (pkgInfo != null) {
            if (pkgInfo.sharedUserId != null && pkgInfo.sharedUserId.equals("android.uid.system")) {
                LogUtils.d("install", apkPath + "is system uid !");
                return true;
            }
            boolean isSystemApp = isSystemApp(pkgInfo.packageName);
            if (isSystemApp)
                return true;
            return false;
        }
        return false;
    }

    private boolean isSystemApp(String pkg) {
        PackageManager pm = mContext.getPackageManager();
        try {
            ApplicationInfo info = pm.getApplicationInfo(pkg, PackageManager.GET_DISABLED_COMPONENTS);
            LogUtils.d("install", " sourceDir:" + info.sourceDir);
            if (info.sourceDir.startsWith("/system") || info.sourceDir.startsWith("system"))
                return true;
            return false;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    private void uninstall(String pkg) throws Exception {
        StringBuilder command1 = new StringBuilder().append("pm uninstall ").append(
                pkg);
        ShellUtils.CommandResult commandResult1 = ShellUtils
                .execCommand(command1.toString(), true, true);
        if (!(commandResult1.successMsg != null
                && (commandResult1.successMsg.toLowerCase().contains("success")))) {
            throw new Exception(commandResult1.errorMsg);
        }
    }

    private void install(String apkfile) throws Exception {
        LogUtils.d("slient_install", " chmod 777 " + apkfile);
        Runtime.getRuntime().exec("chmod 777 " + apkfile);
        AppInfo appinfo = getAPKInfo(apkfile);
        if (appinfo != null && !Android.isPackageInstalled(mContext, appinfo.pkgName)) {
            int preferlocation = getInstallLocation(apkfile);
            LogUtils.d("install", "preferlocation:" + preferlocation);
            switch (preferlocation) {
                case INSTALL_LOCATION_AUTO:
                case INSTALL_LOCATION_INTERNAL_ONLY:
                    StringBuilder command1 = new StringBuilder().append("pm install -r ").append(
                            apkfile);
                    LogUtils.d("slient_install", "INSTALL_LOCATION_INTERNAL_ONLY silent install  cmd:" + command1);
                    ShellUtils.CommandResult commandResult1 = ShellUtils
                            .execCommand(command1.toString(), true, true);
                    if (!(commandResult1.successMsg != null
                            && (commandResult1.successMsg.toLowerCase().contains("success")))) {
                        throw new Exception(commandResult1.errorMsg);
                    }
                    break;
                case INSTALL_LOCATION_PREFER_EXTERNAL:
                    if (SdCardChecker.isSDCardAvaiable()) {
                        String arg = " -s ";
                        if (needInstallSystem(apkfile)) {
                            break;
                        }
                        StringBuilder command2 = new StringBuilder().append("pm install -r " + arg).append(
                                apkfile);
                        LogUtils.d("slient_install", "INSTALL_LOCATION_PREFER_EXTERNAL silent install  cmd:" + command2);
                        ShellUtils.CommandResult commandResult2 = ShellUtils
                                .execCommand(command2.toString(), true, true);
                        if (!(commandResult2.successMsg != null
                                && (commandResult2.successMsg.toLowerCase().contains("success")))) {
                            throw new Exception(commandResult2.errorMsg);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
